<?php

namespace App\Console\Commands\Common;

use App\Models\Common\HolidayModel;
use Illuminate\Console\Command;

class InitHolidayCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'common:init-holiday {year?}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '初始化节假日';

    public function handle()
    {
        if (!$this->argument('year')) {
            $year = date('Y');
        } else {
            $year = $this->argument('year');
        }

        $arr = [
            $year - 1,
            $year,
        ];

        foreach ($arr as $y) {
            $url = "https://timor.tech/api/holiday/year/{$y}/";

            $data = json_decode(file_get_contents($url), true);

            HolidayModel::query()->where('date', 'like', "{$y}%")->delete();

            foreach ($data['holiday'] as $val) {
                HolidayModel::query()->firstOrCreate(['date' => (int)date('Ymd', strtotime($val['date']))],[ 'isHoliday' => (int)$val['holiday'], 'name' => $val['name']]);
            }
        }
    }
}
